<template>
  <!-- 相关方评定计划 -->
  <div class="relatedpartyjudgeplan">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >

        <!-- 左上方菜单栏 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.relatedpartyjudgeplan_delete"
            @click="handleDelete">
            删 除
          </el-button>
        </template>

        <!-- 总分列表格自定义 -->
        <template slot="zf" slot-scope="scope">
          <div>
            <span v-if="scope.row['zf'] && scope.row['zf'] > 0">{{scope.row['zf']}}</span>
            <span v-else>0</span>
          </div>
        </template>

        <!-- 评定状态表格自定义 -->
        <template slot="pdzt" slot-scope="scope">
          <span v-if="assessStatus[scope.row['pdzt']] === undefined">-</span>
          <span v-else>{{assessStatus[scope.row['pdzt']]}}</span>
        </template>

        <!-- 审批状态表格自定义 -->
        <template slot="spzt" slot-scope="scope">
          <span v-if="approveStatus[scope.row['spzt']] === undefined">-</span>
          <span v-else>{{approveStatus[scope.row['spzt']]}}</span>
        </template>

        <!-- 审批表格自定义 -->
        <template slot="approve" slot-scope="scope">
          <el-button
            v-if="scope.row['approvalSetButton'] === 1"
            type="danger"
            size="mini"
            icon="el-icon-setting"
            @click="handleApproveSetting(scope.row)">
            审批设置
          </el-button>
          <el-button
            v-if="scope.row['approvalButton'] === 1"
            type="success"
            size="mini"
            icon="el-icon-document-checked"
            @click="handleApprove(scope.row)">
            审批
          </el-button>
          <span v-if="scope.row['approvalSetButton'] === 0 && scope.row['approvalButton'] === 0">-</span>
        </template>

        <!-- 评定记录表格自定义 -->
        <template slot="record" slot-scope="scope">
          <el-button 
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click="handleEvaluationRecord(scope.row)">
            评定记录
          </el-button>
        </template>

      </avue-crud>

      <!-- 弹窗：评定记录 -->
      <el-dialog 
        title="评定记录"
        append-to-body
        :visible.sync="evaluationRecordDialog"
        :close-on-click-modal="false" 
        :before-close="closeEvaluationRecordDialog"
        width="60%"
        class="evaluation_record_dialog"
      >

        <!-- 内容 -->
        <avue-crud
          :option="evaluationOption"
          :table-loading="evaluationLoading"
          :data="evaluationData"
          :page.sync="evaluationPage"
          ref="evaluationCrud"
          @search-change="evaluationSearchChange"
          @search-reset="evaluationSearchReset"
          @current-change="evaluationCurrentChange"
          @size-change="evaluationSizeChange"
          @refresh-change="evaluationRefreshChange"
        >

          <!-- 状态列表格自定义 -->
          <template slot="status" slot-scope="scope">
            <el-tag size="small" type="success" v-if="scope.row['zf'] !== 0 && scope.row['zf'] !== ''">已评分</el-tag>
            <el-tag size="small" type="danger" v-else>待评分</el-tag>
          </template>

        </avue-crud>

        <!-- 按钮 -->
        <div class="evaluation_record_footer">
          <el-button 
            type="primary"
            size="small"
            @click="closeEvaluationRecordDialog()">
            确 定
          </el-button>
        </div>

      </el-dialog>

      <!-- 弹窗：审批设置 -->
      <approveSetting
        :approveSettingDialog="approveSettingDialog"
        :selectedSettingId="selectedSettingId"
        @confirmApproveSetting="confirmApproveSetting"
        @closeApproveSettingDialog="closeApproveSettingDialog">
      </approveSetting>

      <!-- 审批弹窗 -->
      <approvalRelatedPartyJudgePlan
        :approveDialog="approveDialog"
        :approvePartyId="approvePartyId"
        @confirmApproveRelatedParty="confirmApproveRelatedParty"
        @closeApproveDialog="closeApproveDialog">
      </approvalRelatedPartyJudgePlan>

    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  getRecords,
  setApproveUser
} from "@/api/basedata/interestedpartymange/relatedpartyjudgeplan";
import { mapGetters } from "vuex";
import approveSetting from "./components/approveSetting";
import approvalRelatedPartyJudgePlan from "./components/approvalRelatedPartyJudgePlan";

export default {
  components: {
    approveSetting,
    approvalRelatedPartyJudgePlan
  },
  data() {
    return {
      assessStatus: {
        1: "待评定",
        2: "评定中",
        3: "已评定"
      },
      approveStatus: {
        1: "待审批",
        2: "审批中",
        3: "审批不通过",
        4: "审批完成"
      },
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        index: false,
        selection: true,
        viewBtn: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menuWidth: 200,
        column: [
          {
            label: "单位名称",
            prop: "dwmc",
            search: true,
            hide: true,
            display: false
          },
          {
            label: "单位名称",
            prop: "xgfdw",
            align: "center",
            type: "select",
            dicUrl: "/api/interestedPartyMange/relatedparty/list",
            props: {
              label: "dwmc",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择相关方单位",
              trigger: "change"
            }]
          },
          {
            label: "主持人",
            prop: "pdzcr",
            align: "center",
            value: JSON.parse(localStorage.getItem("saber-userInfo")).content.nick_name,
            rules: [{
              required: true,
              message: "请输入评定主持人",
              trigger: "blur"
            }]
          },
          {
            label: "总分",
            prop: "zf",
            align: "center",
            display: false,
            width: 80,
            slot: true
          },
          {
            label: "评定等级",
            prop: "pddj",
            search: true,
            align: "center",
            width: 100,
            display: false,
            type: "select",
            dicData: [{
              label: '优',
              value: '优'
            }, {
              label: '良',
              value: '良'
            }, {
              label: '中',
              value: '中'
            }, {
              label: '差',
              value: '差'
            }]
          },
          {
            label: "合作项目清单",
            prop: "hzxmqd",
            hide: true,
            type: "textarea",
            span: 24,
            maxlength: 150
          },
          {
            label: "评定人员",
            prop: "pdry",
            hide: true,
            span: 24,
            type: "tree",
            multiple: true,
            checkStrictly: true,
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择评定人员",
              trigger: "change"
            }]
          },
          {
            label: "备注",
            prop: "bz",
            hide: true,
            type: "textarea",
            span: 24,
            maxlength: 150
          },
          {
            label: "评定状态",
            prop: "pdzt",
            align: "center",
            display: false,
            slot: true
          },
          {
            label: "审批状态",
            prop: "spzt",
            align: "center",
            display: false,
            slot: true
          },
          {
            label: "审批",
            prop: "approve",
            align: "center",
            width: 220,
            slot: true,
            display: false
          },
          {
            label: "评定记录",
            prop: "record",
            align: "center",
            slot: true,
            display: false,
            width: 130
          }
        ]
      },
      // 弹窗：评定记录
      evaluationRecordDialog: false,
      selectedRecordId: "",
      evaluationQuery: {},
      evaluationLoading: true,
      evaluationData: [],
      evaluationPage: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      evaluationOption: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 4,
        index: true,
        selection: false,
        addBtn: false,
        index: false,
        refreshBtn: false,
        columnBtn: false,
        menu: false,
        column: [
          {
            label: "单位名称",
            prop: "dwmc",
            align: "center"
          },
          {
            label: "评定人",
            prop: "pdryName",
            align: "center"
          },
          {
            label: "评分",
            prop: "zf",
            align: "center"
          },
          {
            label: "评定等级",
            prop: "pddj",
            align: "center",
            search: true,
            type: "select",
            dicData: [{
              label: '优',
              value: '优'
            }, {
              label: '良',
              value: '良'
            }, {
              label: '中',
              value: '中'
            }, {
              label: '差',
              value: '差'
            }]
          },
          {
            label: "状态",
            prop: "status",
            align: "center",
            slot: true
          },
        ]
      },
      // 弹窗：审批设置
      approveSettingDialog: false,
      selectedSettingId: "",
      // 弹窗：审批
      approveDialog: false,
      approvePartyId: ""
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permission.relatedpartyjudgeplan_add,
          false
        ),
        viewBtn: this.vaildData(
          this.permission.relatedpartyjudgeplan_view,
          false
        ),
        delBtn: this.vaildData(
          this.permission.relatedpartyjudgeplan_delete,
          false
        ),
        editBtn: this.vaildData(
          this.permission.relatedpartyjudgeplan_edit,
          false
        )
      };
    },

    // 勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {

    // 新增
    rowSave(row, done, loading) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.pdry = row.pdry.join(",");
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },

    // 修改
    rowUpdate(row, index, done, loading) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.pdry = typeof row.pdry === "object" ? row.pdry.join(",") : row.pdry;
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开新增、编辑、查看弹窗前
    beforeOpen(done, type) {
      if(type === "edit") {
        if(this.form.editButton === 0) {
          this.$message.warning("当前相关方单位不可编辑!");
          return;
        }
        if(this.form.zf > 0) {
          this.$message.warning("该计划正在评定中，不可编辑!");
          return;
        }
      }
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 加载数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    /**
     * 弹窗：评定记录
    */

    // 打开评定记录弹窗
    handleEvaluationRecord(row) {
      this.evaluationPage.currentPage = 1;
      this.selectedRecordId = row.id;
      this.evaluationOnLoad(this.evaluationPage);
      this.evaluationRecordDialog = true;
    },

    // 搜索条件改变
    evaluationSearchChange(params, done) {
      this.evaluationQuery = params;
      this.evaluationPage.currentPage = 1;
      this.evaluationOnLoad(this.evaluationPage, params);
      done();
    },

    // 清空搜索条件
    evaluationSearchReset() {
      this.evaluationQuery = {};
      this.evaluationOnLoad(this.evaluationPage);
    },

    // 更换页数
    evaluationCurrentChange(currentPage) {
      this.evaluationPage.currentPage = currentPage;
    },

    // 更换每页显示数量
    evaluationSizeChange(pageSize) {
      this.evaluationPage.pageSize = pageSize;
    },

    // 刷新
    evaluationRefreshChange() {
      this.evaluationOnLoad(this.evaluationPage, this.evaluationQuery);
    },

    // 加载数据
    evaluationOnLoad(page, params = {}) {
      this.evaluationLoading = true;
      this.evaluationQuery["planId"] = this.selectedRecordId;
      getRecords(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.evaluationQuery)
      ).then(res => {
        var resData = res.data.data;
        this.evaluationPage.total = resData.total;
        this.evaluationData = resData.records;
        this.evaluationLoading = false;
      });
    },

    // 关闭、取消评定记录弹窗
    closeEvaluationRecordDialog() {
      this.evaluationRecordDialog = false;
      this.selectedRecordId = "";
    },

    /**
     * 弹窗：审批设置
    */

    // 打开审批设置弹窗
    handleApproveSetting(row) {
      this.selectedSettingId = row.id;
      this.approveSettingDialog = true;
    },

    // 确定审批设置
    confirmApproveSetting(approvalUsers) {
      var updateData = this.formatSettingData(approvalUsers);
      setApproveUser(updateData).then(res => {
        if(res.data.success) {
          this.closeApproveSettingDialog();
          this.page.currentPage = 1;
          this.onLoad(this.page);
        }
      });
    },

    // 格式化审批设置数据
    formatSettingData(row) {
      var data = {
        bizId: this.selectedSettingId,
        flowOperatorList: []
      };
      for(let i = 0 ; i < row.length ; i++) {
        data.flowOperatorList.push({
          userId: row[i].id,
          taskOrder: i + 1
        });
      }
      return data;
    },

    // 关闭、取消审批设置弹窗
    closeApproveSettingDialog() {
      this.selectedSettingId = "";
      this.approveSettingDialog = false;
    },

    /**
     * 弹窗：审批
    */

    // 打开审批弹窗
    handleApprove(row) {
      this.approvePartyId = row.id;
      this.approveDialog = true;
    },

    // 确认审批
    confirmApproveRelatedParty() {
      this.closeApproveDialog();
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },

    // 关闭、取消审批弹窗
    closeApproveDialog() {
      this.approvePartyId = "";
      this.approveDialog = false;
    }

  }
};
</script>

<style lang="scss">
.related_party_plan_approve_dialog {
  .avue-form__menu--center {
    text-align: center;
  }
}

.approve_setting_dialog,
.choose_approve_user_dialog {
  .avue-crud__menu,
  .avue-crud__pagination {
    display: none !important;
  }
}

.approve_setting_dialog {
  .el-table__header-wrapper,
  .el-table__empty-block {
    display: none !important;
  }
}
</style>

<style lang="scss" scoped>
.evaluation_record_footer,
.choose_approve_user_footer,
.approve_setting_footer {
  text-align: center;
  margin-top: 15px;

  .el-button {
    width: 100px;
    height: 35px;
  }
}
</style>